package com.xinjian.jianba.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.xinjian.jianba.dao.dwmid.UserInfoDao;
import com.xinjian.jianba.dao.dwmid.UserLocationDao;
import com.xinjian.jianba.dao.dwmid.UserLocationHDao;
import com.xinjian.jianba.dto.UserLocationDto;
import com.xinjian.jianba.enity.UserInfoEnity;
import com.xinjian.jianba.enity.UserLocationEnity;
import com.xinjian.jianba.service.RedisService;
import com.xinjian.jianba.service.UserLocationService;
import com.xinjian.jianba.utils.JianBaEnum;

@Service
public class UserLocationServiceImpl implements UserLocationService {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserLocationServiceImpl.class);

	@Autowired
	private UserLocationDao userLocationDao;

	@Autowired
	private UserInfoDao userInfoDao;

	@Autowired
	private RedisService redisService;

	@Autowired
	private UserLocationHDao userLocationHDao;

	@Value("${spring.meet.geo.db}")
	private String meetDb;

	@Value("${spring.meet.geo.male.db}")
	private String maleMeetDb;

	@Value("${spring.meet.geo.female.db}")
	private String femaleMeetDb;

	/**
	 * 
	 * 用户位置信息更改: 如果用户存在 并且用户状态为可用状态则存储用户位置信息，不抛异常
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void save(UserLocationDto userLocation) {

		UserInfoEnity userInfo = new UserInfoEnity();
		userInfo.setId(Long.parseLong(userLocation.getId()));
		userInfo.setIs_register(1);
		List<UserInfoEnity> isRegist = userInfoDao.select(userInfo);
		if (!CollectionUtils.isEmpty(isRegist)) {
			UserInfoEnity user = isRegist.get(0);
			Integer userStatus = user.getUsrStatus();
			if (userStatus.equals(JianBaEnum.UserStatusEnum.NORMAL.getValue())) {

				UserLocationEnity userLocationEnity = new UserLocationEnity();
				userLocationEnity.setId(userLocation.getId());
				userLocationEnity.setLatfloat(userLocation.getLatfloat());
				userLocationEnity.setLngfloat(userLocation.getLngfloat());
				userLocationEnity.setGeom(userLocation.getGeom());
				LOGGER.info("-------UserLocation-----geom--------" + userLocation.getGeom());
				userLocationEnity.setAddDate(new Date());
				userLocationEnity.setAddTime(new Date());
				int line = userLocationDao.insert(userLocationEnity);
				LOGGER.info("-------UserLocation-----save--------" + line);
				// 缓存初始化
				initeCache();
				//设置用户缓存
				setUserCache(userLocation);

			}
		}

	}

	/**
	 * 设置男，女，或者通用男女缓存数据
	 *
	 */
	private void setUserCache(UserLocationDto userLocation) {
		// 通用男女缓存位置信息
		redisService
				.geoadd(meetDb, userLocation.getId(), userLocation.getLngfloat().doubleValue(), userLocation.getLatfloat().doubleValue());

		UserInfoEnity userEnity = userInfoDao.findById(Long.parseLong(userLocation.getId()));
		if (userEnity != null && userEnity.getSex() != null) {
			//如果是男
			if (userEnity.getSex() == 0) {
				redisService.geoadd(maleMeetDb, userLocation.getId(), userLocation.getLngfloat().doubleValue(), userLocation.getLatfloat()
						.doubleValue());
			} else if (userEnity.getSex() == 1) {
				redisService.geoadd(femaleMeetDb, userLocation.getId(), userLocation.getLngfloat().doubleValue(), userLocation.getLatfloat()
						.doubleValue());
			}
		}
	}

	/**
	 * 缓存初始化
	 */
	private void initeCache() {

		UserInfoEnity userInfo = new UserInfoEnity();
		userInfo.setIs_register(1);
		List<UserInfoEnity> userList = userInfoDao.select(userInfo);

		Set<String> idSet = new HashSet<String>();
		//性别map key=userId ,value=sex
		Map<String, Integer> sexMap = new HashMap<String, Integer>();
		if (!CollectionUtils.isEmpty(userList) && userList.size() > 0) {
			userList.stream().forEach(user -> {
				sexMap.put(user.getId() + "", user.getSex());
				idSet.add(user.getId() + "");
			});
		}

		Long size = redisService.count(meetDb);
		if (size == null || size == 0) {
			List<UserLocationEnity> allList = userLocationHDao.findAll();
			if (!CollectionUtils.isEmpty(allList) && allList.size() > 0) {
				allList.stream().forEach(localtion -> {
					if (idSet.contains(localtion.getId())) {

						//通用男女缓存
						redisService.geoadd(meetDb, localtion.getId(), localtion.getLngfloat().doubleValue(), localtion.getLatfloat()
								.doubleValue());

						//只设置男或者女缓存数据
						Integer sex = sexMap.get(localtion.getId());
						if (sex != null) {
							if (sex.intValue() == JianBaEnum.SexEnum.MALE.getValue()) {
								redisService.geoadd(maleMeetDb, localtion.getId(), localtion.getLngfloat().doubleValue(), localtion
										.getLatfloat().doubleValue());
							} else if (sex.intValue() == JianBaEnum.SexEnum.FEMALE.getValue()) {
								redisService.geoadd(femaleMeetDb, localtion.getId(), localtion.getLngfloat().doubleValue(), localtion
										.getLatfloat().doubleValue());
							}
						}
					}

				});
			}
		}
	}

}
